package com.xigua._搜索或回溯算法;

/**
 * @author LiRongHua
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: 给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 
 * word 存在于网格中，返回 true ；否则，返回 false 。单词必须按照字母顺序，
 * 通过相邻的单元格内的字母构成，其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

 * @date 2022/3/1822:19
 */
public class _剑指Offer12_矩阵中的路径 {

    public static void main(String[] args) {
        char board[][] = new char[][]{{'C','A','A'},{'A','A','A'},{'B','C','D'}};
        String word = "AAB";
        System.out.println(exist(board, word));

    }

    public static boolean exist(char[][] board, String word) {
        int n = board.length;
        int m = board[0].length;
        char[] w = word.toCharArray();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (dfs(board,w,i,j,0)) return true;
            }
        }
        return false;
    }
    static boolean  dfs(char[][] board, char[] word, int i, int j, int k) {
        if (i<0 || j<0 || i>=board.length ||j>=board[0].length || board[i][j] != word[k]  ) return false;
        if (k == word.length-1) return true;
        board[i][j] = '\0';
        boolean ans = dfs(board,word,i+1,j,k+1) || dfs(board,word,i-1,j,k+1) ||
                dfs(board,word,i,j+1,k+1) || dfs(board,word,i,j-1,k+1);
        board[i][j] = word[k];
        return ans;
    }

}
